package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_list

import android.content.Intent
import android.view.View
import android.widget.FrameLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.interstitial.api.ATInterstitial
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.banner_ad.TopOnBannerAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.banner_ad.TopOnBannerAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityHeartRateHistoryListBgBinding
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.BpHeartRateViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_guide.BpHeartRateGuideActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_report.BpHeartRateReportActivity
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.throttleClick
import com.bp.hearthealth.pulse.lnapps.bp_view.BPSpacingItemDecoration
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import org.koin.androidx.viewmodel.ext.android.viewModel

class BpHeartRateHistoryListActivity : BpBaseActivity<ActivityHeartRateHistoryListBgBinding>() {

    private var nativeAd: NativeAd? = null
    private val viewModel: BpHeartRateViewModel by viewModel()
    private val heartAdapter = BpHeartRateAdapter()
    private var view: View? = null
    private var toponBannerManager: TopOnBannerAdManager? = null

    override fun initListener() {
        super.initListener()

        binding.apply {
            viewModel = this@BpHeartRateHistoryListActivity.viewModel
            constraintMearsure.throttleClick {
                this@BpHeartRateHistoryListActivity.viewModel.getIsFirstOpenDetection(Constants.USER_ID)
            }
        }
    }

    private fun initRecyclerView() {
        binding.apply {
            val layoutManager = LinearLayoutManager(activity)
            layoutManager.orientation = LinearLayoutManager.VERTICAL
            recyclerView.layoutManager = layoutManager
            recyclerView.adapter = heartAdapter
            val marginBottom = resources.getDimensionPixelSize(R.dimen.rate_list_margin_bottom)
            val marginTop = resources.getDimensionPixelSize(R.dimen.rate_list_margin_top)
            recyclerView.addItemDecoration(BPSpacingItemDecoration(marginBottom, marginTop))
            heartAdapter.setOnItemClickLisener(object :
                BpHeartRateAdapter.OnHeartRateItemClickListener {
                override fun onHeartRateItemClick(id: Long) {
                    //展示插页广告
//                    loadAdMobInsertAd(id)
                    loadTopOnInsertAd(id)
                }
            })
        }
    }

    override fun initData() {
        super.initData()
        binding.lifecycleOwner = this
        if (!AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl)) {
            TopOnInterAdManager.initManualLoadInterstitialAd(this)
            TopOnInterAdManager.manualLoadAd()
        }
        initRecyclerView()
        (activity as BpHeartRateHistoryListActivity).baseObserver()
        registerObserver()
        viewModel.loadHeartRateList(Constants.USER_ID)
//        loadAdmobNativeAd()
        toponBannerManager = TopOnBannerAdManager()
        toponBannerManager!!.initBannerView(this)
        loadTopOnBannerAd()
        //心率历史页展示
        AppsFlyerUtils.trackEvent("hr_history_show")
    }

    private fun loadTopOnBannerAd() {
        if (toponBannerManager?.getBannerView() != null) {
            if (toponBannerManager?.getBannerView()?.checkAdStatus()?.isReady == true) {
                setTopOnBannerView()
            } else {
                toponBannerManager?.setBannerListener(object : TopOnBannerAdListener {
                    override fun onBannerShow(entity: ATAdInfo) {
                        LogUtil.iTopOn("TopOn 【横幅广告】 BpMainActivity onBannerShow")
                    }

                    override fun onBannerLoaded() {
                        setTopOnBannerView()
                    }
                })
            }
        }
    }

    private fun setTopOnBannerView() {
        toponBannerManager?.getBannerView()?.setBannerAdListener(null)
        toponBannerManager?.setBannerListener(null)
        binding.bannerAdContainer.visibility = View.VISIBLE
        binding.bannerAdContainer.removeAllViews()
        binding.bannerAdContainer.addView(
            toponBannerManager?.getBannerView(),
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                binding.bannerAdContainer.layoutParams.height
            )
        )
    }

    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadAdmobNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID,"f6647208b8ea9a")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate History页_原生广告】")
                AppsFlyerUtils.trackEvent("ad_native_hr_history_show")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    private fun registerObserver() {
        viewModel.isFirstOpenDetection.observe(this) { result ->
            if (result) {
                startActivity(Intent(activity, BpHeartRateGuideActivity::class.java))
            } else {
                //校验权限
                (activity as BpHeartRateHistoryListActivity).requestPermission()
            }
        }
        viewModel.heartRateListResult.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response.isNullOrEmpty()) {
                heartAdapter.setHeartRateListData(emptyList())
                BpLiveDataBus.with<Boolean>(Constants.REFRESH_HEART_RATE).postData(true)
                viewModel.listSize.value = 0
                return@Observer
            }
            viewModel.listSize.value = response.size
            heartAdapter.setHeartRateListData(response)
        })
        viewModel.listSize.observe(this) { size ->
            if (size == 0) {
                if (view != null) {
                    view!!.visibility = View.VISIBLE
                    return@observe
                }
                view = binding.viewStub.viewStub?.inflate()
            } else {
                view?.visibility = View.GONE
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.loadHeartRateList(Constants.USER_ID)
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        binding.includeToolbar.apply {
            ImmersionBar.with(this@BpHeartRateHistoryListActivity).titleBar(toolbar).init()
            tvBack.text = getString(R.string._history_str)
            tvBack.throttleClick {
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        }
    }


    /**
     * 插页广告
     *
     *  ○ 点击Back入口，展示插页广告，该条检测数据保存
     *      ■ 插页广告资源加载到，立即展示，广告关闭后自动跳转至上一级页面
     *      ■ 插页广告资源未加载到，自动跳转至上一级页面
     *
     *      空:销毁
     *      非空:跳转新activity
     */
    private fun loadAdMobInsertAd(vararg id: Long) {
        AdMobInterstitialAdManager.setInterstitialAdListener(object : AdMobInterstitialAdListener {
            override fun onAdDismissedFullScreenContent() {
                startJumpActivity(id)
            }

            override fun onAdFailedToShowFullScreenContent() {
                startJumpActivity(id)
            }

            override fun onNotReady() {
                startJumpActivity(id)
            }

            override fun onAdShowedFullScreenContent() {
                //点击返回入口后_插页广告
                AppsFlyerUtils.trackEvent("ad_inter_hr_history_back_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471f2797a10")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate历史页点击返回入口后_插页广告】")
            }
        })
        AdMobInterstitialAdManager.showInterstitialAd(this)
    }

    private fun loadTopOnInsertAd(vararg id: Long) {
        TopOnInterAdManager.setManualLoadListener(object : TopOnInterstitialAdListener {
            override fun onInterstitialAdShow(entity: ATAdInfo) {
                //点击返回入口后_插页广告
                AppsFlyerUtils.trackEvent("ad_inter_hr_history_back_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID,"f66471f2797a10")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate历史页点击返回入口后_插页广告】")
            }

            override fun onFireBaseAdIsClosed() {
                startJumpActivity(id)
            }

//            override fun onInterstitialAdLoaded() {
//                LogUtil.iTopOn("插页广告 onInterstitialAdLoaded 回调")
//                if (TopOnInterAdManager.isAdReady()) {
//                    TopOnInterAdManager.mInterstitialAd!!.show(this@BpHeartRateHistoryListActivity)
//                } else {
//                    startJumpActivity(id)
//                }
//            }

            override fun onInterstitialAdClose(entity: ATAdInfo) {
                startJumpActivity(id)
            }

            override fun onInterstitialAdLoadFail(adError: AdError) {
                startJumpActivity(id)
            }

            override fun onInterstitialAdVideoError(adError: AdError) {
                startJumpActivity(id)
            }

            override fun onNotReady() {
                startJumpActivity(id)
            }
        })
        TopOnInterAdManager.showInterstitialAd(this)
    }

    private fun startJumpActivity(id: LongArray) {
        if (id.isEmpty()) {
            finish()
        } else {
            val intent = Intent(
                activity, BpHeartRateReportActivity::class.java
            )
            intent.putExtra("id", id[0])
            intent.putExtra("type", Constants.HEART_LIST)
            startActivity(intent)
        }
    }


    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
//        loadAdMobInsertAd()
        loadTopOnInsertAd()
    }

    override fun onDestroy() {
        if (_binding != null) {
            binding.bannerAdContainer.removeAllViews()
        }
        super.onDestroy()
        toponBannerManager?.releaseBannerAd()

        TopOnInterAdManager.setManualLoadListener(null)
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }
}